package com.mock.ems.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值记录
 * @author whx
 * @date 2017/08/19
 */
public class RechargeRecordController extends Controller {

    public void index()  {
        renderJsp("/rechargerecord_list.jsp");
    }

    public void pagination() {
        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        String selectSql = "select *";
        StringBuilder sqlExceptSql = new StringBuilder(" from user_recharge_record where 1 = 1");
        List<Object> params = new ArrayList<Object>();

        String nickName = getPara("nickName");
        if (StringUtil.isNotEmpty(nickName)) {
            List<Record> userRecordList = Db.find("select id from user where nick_name like ? ",'%' + nickName.trim() + '%');
            if (CollectionUtil.isNotEmpty(userRecordList)) {
                sqlExceptSql.append(" and user_id in ( ");
                userRecordList.stream().forEach(item -> {
                    sqlExceptSql.append("?,");
                    params.add(item.getLong("id"));
                });
                sqlExceptSql.deleteCharAt(sqlExceptSql.length() - 1);
                sqlExceptSql.append(") ");
            }
        }

        String orderNo = getPara("order_no", "");
        if (StringUtil.isNotEmpty(orderNo.trim())) {
            sqlExceptSql.append( " and order_no = ?");
            params.add(orderNo.trim());
        }

        int rechargeType = getParaToInt("recharge_type", 0);
        if (0 != rechargeType) {
            sqlExceptSql.append( " and recharge_type = ?");
            params.add(rechargeType);
        }

        int status = getParaToInt("status", -1);
        if (status != -1) {
            sqlExceptSql.append( " and status = ?");
            params.add(status);
        }

        Page<Record> page = Db.paginate(pageNumber, limit, selectSql, sqlExceptSql.toString(), params.toArray());
        List<Record> recordList = page.getList();
        if(CollectionUtil.isNotEmpty(recordList)){
            recordList.stream().forEach(item->{
                Record user = Db.findById("user",item.getLong("user_id"));
                item.set("nick_name",user.getStr("nick_name"));
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", page.getTotalRow());
        returnMap.put("rows", page.getList());
        renderJson(returnMap);
    }

}
